import { produce } from 'immer'
import { type FC, memo, useState } from 'react'
import classNames from 'classnames'
import { useDebounceFn, useMemoizedFn } from 'ahooks'
import contentStyle from '../../index.module.scss'
import Slider from '../slider'
import styles from '../index.module.scss'
import { useCustomizationStore, usePersonalDetailsStore } from '@/store'
import { updateCustomization } from '@/service'

interface IndexProps {
}
const Index: FC<IndexProps> = () => {
  const { customization, updateSpacing, addCustomization } = useCustomizationStore(state => state, (o, n) => {
    return o.customization.spacing === n.customization.spacing
  })

  const { personalDetails } = usePersonalDetailsStore(state => state, (o, n) => {
    return o.personalDetails.id === n.personalDetails.id
  })

  const [sliders] = useState([
    { name: 'marginHorizontal', label: '水平边距' },
    { name: 'marginVertical', label: '垂直边距' },
  ])
  const change = (data) => {
    updateSpacing(data)
  }
  const updateValue = (params) => {
    return updateCustomization({
      ...params,
    })
  }
  const { run } = useDebounceFn(
    (data) => {
      updateValue({
        updates: [
          {
            path: data.path,
            value: data.value,
          },
        ],
        id: customization.id,
      })
    },
    {
      wait: 1000,
    },
  )
  const onChange = useMemoizedFn((v, name) => {
    const data = produce(customization.spacing, (draft) => {
      if (!draft.module) {
        draft.module = {
          marginHorizontal: 0,
          marginVertical: 0
        }
      }
      draft.module[name] = v
    })
    change(data)
    if (customization.id) {
      run({
        path: `spacing.module.${name}`,
        value: v,
      })
    }
    else if (personalDetails.id) {
      addCustomization(personalDetails.id)
    }
  })
  return (
    <div className={classNames(styles.spacing)}>
      <h1 className={contentStyle.subtitle} style={{ marginTop: '30px' }}>模块边距设置</h1>
      {
        sliders.map((s) => {
          return <div key={s.name} style={{ marginBottom: '10px' }}>
            <Slider value={(customization.spacing.module as any)?.[s.name]} item={s} onChange={v => onChange(v, s.name)} />
          </div>
        })
      }

    </div>
  )
}

export default memo(Index, () => {
  return true
})
